<?php

namespace App\Http\Controllers\Api;

use App\Constants\CodeResponse;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\JsonResponse;

class ApiController extends Controller
{
    /**
     * 格式化统一成功输出结果
     * @param  null  $data
     * @param  string  $info
     * @return JsonResponse
     */
    protected function success($data=null, string $info=''): JsonResponse
    {
        list($errno,$errormessage) = CodeResponse::SUCCESS;
        $ret = ['errno' => $errno,'errmsg' => $info ?: $errormessage];
        if (!is_null($data)) {
            if (is_array($data)) {
                $data = array_filter($data, function ($item) {
                    return $item !== null;
                });
            }
            $ret['data'] = $data;
        }
        return response()->json($ret);
    }

    /**
     * 格式化统一失败输出结果
     * @param  array  $codeResponse
     * @param  string  $info
     * @return JsonResponse
     */
    protected function fail(array $codeResponse,$info=''): JsonResponse
    {
        list($errno,$errormessage) = $codeResponse;
        $ret = ['errno' => $errno,'errmsg' => $info ?: $errormessage];
        return response()->json($ret);
    }

    protected function successPaginate(LengthAwarePaginator $page): array
    {
        $total = $page->total();
        return [
            'total' => $page->total(),
            'page' => $total == 0 ? 0 : $page->currentPage(),
            'limit' => $page->perPage(),
            'pages' => $total == 0 ? 0 : $page->lastPage(),
            'list' => $list ?? $page->items()
        ];
    }
}